package org.sdau.rotten.library.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import cn.hutool.core.convert.Convert;
import cn.hutool.crypto.SecureUtil;

import com.alibaba.fastjson.JSONObject;
import org.sdau.rotten.library.entity.Appointment;
import org.sdau.rotten.library.entity.Book;
import org.sdau.rotten.library.entity.User;
import org.sdau.rotten.library.service.BookService;
import org.sdau.rotten.library.service.UserService;
import org.sdau.rotten.library.DTO.JsonData;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;
@Controller
@Slf4j
@RequestMapping("custom")
public class CustomController {
    @Resource(name = "userServiceImpl")
    private UserService userService;
    @Resource(name = "bookServiceImpl")
    private BookService bookService;
    LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(100, 30);
//    @RequestMapping("/getCode")
//    public void getCode(HttpServletResponse response) {
//        // 随机生成 4 位验证码
//        RandomGenerator randomGenerator = new RandomGenerator("0123456789abcdefg", 4);
//        // 定义图片的显示大小
//        lineCaptcha = CaptchaUtil.createLineCaptcha(100, 30);
//        response.setContentType("image/jpeg");
//        response.setHeader("Pragma", "No-cache");
//        try {
//            // 调用父类的 setGenerator() 方法，设置验证码的类型
//            lineCaptcha.setGenerator(randomGenerator);
//            // 输出到页面
//            lineCaptcha.write(response.getOutputStream());
//            // 打印日志
//            log.info("生成的验证码:{}", lineCaptcha.getCode());
//            /* lineCaptcha.verify();验证*/
//            // 关闭流
//            response.getOutputStream().close();
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//    }
    @PostMapping("/login")
    public String login(@RequestParam("username")String username,
                              @RequestParam("password")String password,
                              HttpServletRequest request) {
//        if( !lineCaptcha.verify(code))
//        {
//            modelAndView.addObject("msg","验证码错误");
//            modelAndView.setViewName("/index");
//            return modelAndView;
//        }
        Subject subject = SecurityUtils.getSubject();//shiro整合
        String md5Str = SecureUtil.md5(password);
        UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(
                username,
                md5Str);
        User user = userService.isExist(username,md5Str);
        if(user==null) {
            return "redirect:/loginPage";
        }
        request.getSession().setAttribute("username",user.getId());
        request.getSession().setAttribute("user",user);
        subject.login(usernamePasswordToken);
        return "redirect:/custom/myAppoint";

    }

    @PostMapping("/register")
    public ModelAndView register(@RequestParam("userId") Integer id,
                                 @RequestParam("password") String password,
                                 @RequestParam("authority") String authority,
                                 @RequestParam("email") String email) {

        User user = new User();
        user.setId(id);
        user.setEmail(email);
        user.setAuthority(authority);
        user.setPassword(password);

        userService.register(user);
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("list",bookService.search(""));
        modelAndView.setViewName("/login");
        return modelAndView;

    }


    @RequestMapping(value = "/logout")
    public String logout(HttpServletRequest request) {
        Subject subject = SecurityUtils.getSubject();
        subject.logout();

        return "redirect:/";
    }



    @GetMapping("/listBook")
    private ModelAndView list(ModelAndView model,@RequestParam("bookName")String bookName,
                              HttpServletRequest request) {
        List<Book> list = bookService.search(bookName);
        request.getSession().setAttribute("list",list);
        System.out.println(list.get(0));
        model.addObject("list",list);
        model.setViewName("borrow_book");
        return model;
    }

    @GetMapping("/myAppoint")
    public ModelAndView myAppoint(ModelAndView modelAndView ,
                                  HttpServletRequest request)
    {
        User user = (User) request.getSession().getAttribute("user");
        String userId = String.valueOf(user.getId());

        List<Appointment> appointmentList = userService.myAppoint(userId);
        System.out.println(appointmentList.size());
        request.getSession().setAttribute("list",appointmentList);
        modelAndView.addObject("list",appointmentList);
        modelAndView.setViewName("index");
        return  modelAndView;
    }

    @GetMapping("/returnBook")
    public JsonData returnBook(@RequestParam("book_id") String bookId,HttpServletRequest request)
    {
        User user = (User) request.getSession().getAttribute("user");
        String userId = String.valueOf(user.getId());
        if(bookService.returnBook(Convert.toInt(bookId),Convert.toInt(userId)))
            return JsonData.buildSuccess("还书成功");
        else
            return JsonData.buildError("还书失败");

    }

    @ResponseBody
    @GetMapping("/timeout")
    public JSONObject timeout(HttpSession session) throws Exception {

        JSONObject obj = new JSONObject();

        String userCode = (String) session.getAttribute("user");

        obj.put("data", userCode);

        obj.put("code", 0);

        obj.put("message", "长时间未操作，身份已过期，请重新登录！");

        return obj;
    }

   /* @GetMapping("/book_brief")
    public JSONObject script(@RequestParam("book_name")String book_name)
    {


    }*/

}
